package org.apache.axis2.json.Utils;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.apache.axis2.json.exception.Axis2JsonException;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class JsonUtils implements JsonConstant{

    private JsonReader reader;
    private static Gson gson = new Gson();

    public static Object invokeServiceClass(JsonReader reader ,
                                            Object service,
                                            Method operation ,
                                            Class[] paramClasses ,
                                            int paramCount) throws IOException, InvocationTargetException,
                                                                        IllegalAccessException, Axis2JsonException {
        // TODO- invoke service method with the correct method arguments
        if (paramCount > 1) {
            reader.beginArray();
        }
        Object[] methodParam = new Object[paramCount];
        Gson gson = new Gson();
        String[] argNames = new String[paramCount];
        
        int i = 0;
        for (Class paramType : paramClasses) {
            reader.beginObject();
            argNames[i] = reader.nextName();
            methodParam[i] = gson.fromJson(reader, paramType);   // gson handle all types well and retuen an object from it
            reader.endObject();
            i++;
            //TODO- check for Enum , Collection types and handle them

        }
        if (paramCount > 1) {
            reader.endArray();
            reader.endObject();
        }

        return  operation.invoke(service, methodParam);
        
    }
    
    public static void processResponse(JsonWriter writer ,Method operation ,  Object retObj , String response ) throws IOException {
        // TODO- generate response message in correct format and Writer to jsonWriter

        Class returnType = operation.getReturnType();
        Gson gson = new Gson();
        writer.beginObject();
        writer.name(response);
//        writer.beginObject();
//        writer.name(RETURN);
        gson.toJson(retObj ,returnType ,writer);
//        writer.endObject();
        writer.endObject();
        writer.flush();
        writer.close();



    }




}
